package com.qlhx.controller;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.qlhx.common.model.ApiResult;
import com.qlhx.common.util.DateUtil;
import com.qlhx.common.util.IpUtil;
import com.qlhx.model.Facedevice;
import com.qlhx.model.FrushFaceRecord;
import com.qlhx.model.VisitorInfo;
import com.qlhx.mq.MQSender;
import com.qlhx.service.TDX8FaceService;
import com.qlhx.service.TDXFaceService;
import com.qlhx.service.impl.FaceDeviceServiceImpl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * Created by yxn on 2018-06-04.
 */

@Api(value = "人脸闸机接口", description = "人脸闸机接口")
@CrossOrigin(maxAge = 3600)
@Controller
@Scope(value = "prototype")
@RequestMapping("aiface")
public class AIFaceDeviceController {
	private  final Logger logger = LoggerFactory.getLogger(AIFaceDeviceController.class);

    @Autowired
    FaceDeviceServiceImpl faceDeviceServiceImpl;

    @Autowired
    TDXFaceService tdxFaceService;

    @Autowired
    TDX8FaceService tdx8FaceService;
    
    @Autowired
    private MQSender sender;


//    private String rmsurl = IConfig.getInstance().get("rmsurl");


    private  boolean  isFail = false;

    @ApiOperation(value = "根据设备id返回人脸设备", notes = "根据设备id返回人脸设备")
    @RequestMapping(value = "getfacedevicebyid/{id}", method = RequestMethod.GET, produces = {"application/json"})
    public
    @ResponseBody
    ApiResult<Facedevice> getfacedevicebyid(@PathVariable String id, HttpServletRequest request) {

        ApiResult<Facedevice> result = new ApiResult<Facedevice>();
        try {
            Facedevice facedevice = faceDeviceServiceImpl.selectByPrimaryKey(Integer.parseInt(id));
            if (facedevice != null) {
                result.setContent(facedevice);
            } else {
                result.setCode(9000);
                result.setMsg("未查询到设备");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.getErrorResult(e);
        }
        return result;
    }


	@ApiOperation(value = "设备列表", notes = "设备列表")
	@RequestMapping(value = "list", method = RequestMethod.POST, produces = { "application/json" })
	public @ResponseBody List<Facedevice> list(HttpServletRequest request) {
		List<Facedevice> deviceList = faceDeviceServiceImpl.list(null);
		return deviceList;
	}



    @ApiOperation(value = "添加人脸设备", notes = "添加人脸设备")
    @RequestMapping(value = "add", method = RequestMethod.POST, produces = {"application/json"})
    public
    @ResponseBody
    ApiResult<String> add(@RequestBody Facedevice facedevice, HttpServletRequest request) {
        ApiResult<String> result = new ApiResult<String>();
        try {
            Facedevice facedeviceTemp = faceDeviceServiceImpl.selectByIp(facedevice.getIp());
            if (facedeviceTemp == null) {
                faceDeviceServiceImpl.insertSelective(facedevice);
                result.setContent(facedevice.getId()+"");
            } else {
                result.setCode(ApiResult.PARAM_ERROR);
                result.setMsg("ip地址在设备中已经存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.getErrorResult(e);
        }
        return result;
    }

    @ApiOperation(value = "修改人脸设备", notes = "修改人脸设备")
    @RequestMapping(value = "update", method = RequestMethod.POST, produces = {"application/json"})
    public
    @ResponseBody
    ApiResult<String> update(@RequestBody Facedevice facedevice, HttpServletRequest request) {
        ApiResult<String> result = new ApiResult<String>();
        try {
            if (facedevice.getId() == null) {
                result.setCode(ApiResult.PARAM_ERROR);
                result.setMsg("主键id不能为空");
            } else {
                Facedevice facedeviceTemp = faceDeviceServiceImpl.selectByIpandId(facedevice.getIp(), "" + facedevice.getId());
                if (facedeviceTemp == null || (facedeviceTemp != null && facedeviceTemp.getId() == null)) {
                    faceDeviceServiceImpl.updateByPrimaryKeySelective(facedevice);
                } else {
                    result.setCode(ApiResult.PARAM_ERROR);
                    result.setMsg("ip地址在设备中已经存在");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.getErrorResult(e);
        }
        return result;
    }

    @ApiOperation(value = "删除人脸设备", notes = "删除人脸设备")
    @RequestMapping(value = "delete/{id}", method = RequestMethod.GET, produces = {"application/json"})
    public
    @ResponseBody
    ApiResult<String> update(@PathVariable Integer id, HttpServletRequest request) {
        ApiResult<String> result = new ApiResult<String>();
        try {
            if (id == null) {
                result.setCode(ApiResult.PARAM_ERROR);
                result.setMsg("主键id不能为空");
            } else {
                faceDeviceServiceImpl.deleteByPrimaryKey(id);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.getErrorResult(e);
        }
        return result;
    }

    @ApiOperation(value = "人脸注册", notes = "人脸注册")
    @RequestMapping(value = "reguserface", method = RequestMethod.POST, produces = {"application/json"})
    public
    @ResponseBody
    ApiResult<String> reguserface(@RequestBody VisitorInfo visitorInfo) {
        ApiResult<String> result = new ApiResult<String>();
        Map resultMap = null;
        try {
            isFail = false;
            String deviceIds = visitorInfo.getDeviceIds();
            if (StringUtils.isBlank(deviceIds)) {
                result.setCode(ApiResult.PARAM_ERROR);
                result.setMsg("设备id不能为空");
            } else {
                String[] deviceIdArr = deviceIds.split(",");
//                boolean isFail = false;
                String errMsg = "";//失败信息合集
                List<Integer> successTDXList = new ArrayList<Integer>();//成功的腾达迅设备
                List<Integer> successTDX8List = new ArrayList<>();


                ExecutorService exec = Executors.newCachedThreadPool();
                List<ApiResult<String>> failResult= new ArrayList<>();

                for (String devicdId : deviceIdArr) {



                    if (!isFail) {
                        Integer devicdId_int = 0;
                        try {
                            devicdId_int = Integer.parseInt(devicdId);
                        }catch (Exception ex)
                        {
                            continue;
                        }
                        Facedevice faceDevice = faceDeviceServiceImpl.selectByPrimaryKey(devicdId_int);
                        if(faceDevice != null)
                        {

                        	switch (faceDevice.getModel()) {
                                case "TDX":
                                {
                                    //腾达迅
                                    //1,注册人员
                                    /** 原有单线程
                                    resultMap = tdxFaceService.regCard(Integer.valueOf(devicdId) , visitorInfo);
                                    if (resultMap.get("code").equals("1000")) {
                                        successTDXList.add(devicdId_int);
                                    } else {
                                        isFail = true;
                                        errMsg += resultMap.get("msg");
                                    }
                                     */

                                    Runnable task = new Runnable() {
                                        @Override
                                        public void run() {
                                            Map<String, String> tempResult = tdxFaceService.regCard(faceDevice, visitorInfo);
                                            if (tempResult == null || tempResult.get("code") == null || (!tempResult.get("code").equals("1000"))) {

                                                isFail = true;
                                            } else {
                                                successTDXList.add(faceDevice.getId());
                                            }
                                        }
                                    };
                                    exec.submit(task);
                                    break;
                                }
                                case "TDX8":
                                {

                                    Runnable task = new Runnable() {
                                        @Override
                                        public void run() {
                                            Map<String, String> tempResult = tdx8FaceService.regCard(faceDevice, visitorInfo);
                                            if (tempResult == null || tempResult.get("code") == null || (!tempResult.get("code").equals("1000"))) {
                                                isFail = true;
                                            } else {
                                                successTDX8List.add(faceDevice.getId());
                                            }
                                        }
                                    };
                                    exec.submit(task);

                                    break;
                                }
                            default:
                                break;
                        }
                       }
                        
                    }
                }
                exec.shutdown();
                while(true)
                {
                    if(exec.isTerminated())
                    {
                        logger.info("=====所有的子线程都结束了！=========");
                        break;
                    }
                    Thread.sleep(200);
                }

                if (isFail)//有失败的设备，需要回滚
                {
                    result.setCode(ApiResult.OPERATION_ERROR);
//                    result.setMsg("失败的设备 海清：" + StringUtils.join(successHQList, ",") +
//                            " 海康设备有：" + StringUtils.join(successHCList, ",")+ " 腾达迅设备有：" + StringUtils.join(successTDXList, ","));
                    result.setMsg("人脸注册失败,请重新拍照");
                    result.setCause(errMsg);

                    for (Integer hcDeviceId : successTDXList) {
                        tdxFaceService.delCard(hcDeviceId, visitorInfo);
                    }

                    for (Integer hcDeviceId : successTDX8List) {
                        tdx8FaceService.delCard(hcDeviceId, visitorInfo);
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.getErrorResult(e);
            logger.error("执行注册人脸接口异常", e);

        }
        return result;
    }


    @ApiOperation(value = "验证结果通知", notes = "验证结果通知")
    @RequestMapping(value = "Verify", method = RequestMethod.POST, produces = {"application/json"})
    public
    @ResponseBody
    ApiResult Verify(@RequestBody Map hqVerifyInfo, HttpServletRequest request) {

       // System.out.println("验证结果上报" + JSON.toJSONString(hqVerifyInfo));

        ApiResult result = new ApiResult();

        return result;
    }

//    @ApiOperation(value = "心跳", notes = "心跳")
//    @RequestMapping(value = "heartbeat", method = RequestMethod.POST, produces = {"application/json"})
//    public
//    @ResponseBody
//    Map heartbeat(@RequestBody Map hqheartbeatInfo, HttpServletRequest request)
//    {
//        if (hqheartbeatInfo != null && "HeartBeat".equals(hqheartbeatInfo.get("operator"))) {
//            JSONObject info = JSONObject.parseObject(JSON.toJSONString(hqheartbeatInfo));
//            if (info != null) {
//                JSONObject deviceinfo = info.getJSONObject("info");
//
//                String deviceid = deviceinfo.getString("DeviceID");
//                String time = deviceinfo.getString("Time");
//
//                System.out.println("设备：" + deviceid + "心跳时间" + time);
//            }
//        }
//        return hqheartbeatInfo;
//    }

    @ApiOperation(value = "TDX8识别回调", notes = "TDX8识别回调")
    @RequestMapping(value = "TDX8CallBack", method = RequestMethod.POST)
    public
    @ResponseBody
     String  TDX8CallBack( String deviceKey, String personId, String time, String type, String path, HttpServletRequest request)
    {
        try {

            //获取IP 松耦合，不管返回值
            String ip = IpUtil.getIpAddr(request);
            String frushFaceUrl = "" + "/fkbindface/FrushFaceRecord";
            Facedevice facedevice = faceDeviceServiceImpl.selectByIp(ip);
            if (facedevice != null) {
                //String time = time;
                Long ltime = Long.parseLong(time);
                Date d = new Date(ltime);
                time= DateUtil.dateToStringWithTime(d);
                //返回只有ID，在TDX设备中，ID和卡号一致。必须要有卡号，原因是卡号需要下发门禁
                String cardNo = personId;
                FrushFaceRecord frushFaceRecord = new FrushFaceRecord(facedevice.getId(), facedevice.getInorout(), time, cardNo);
                String strJson = JSON.toJSONString(frushFaceRecord);
//                String respose = HTTP.post(frushFaceUrl, strJson);
//                logger.info(String.format("TDX8CallBack:ip:%s,return%s", ip, respose));
            }
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error(String.format("执行回调异常%s", e.getStackTrace()));
        }
//        Map map = new HashedMap();
//
//        map.put("result",1);
//        map.put("success","成功");
        return "{\"result\":1,\"success\":ture}";
    }


    @ApiOperation(value = "tdx识别回调", notes = "tdx识别回调")
    @RequestMapping(value = "tdxCallBack", method = RequestMethod.POST, produces = {"application/json"})
    public
    @ResponseBody
    Map tdxCallBack(@RequestBody Map info, HttpServletRequest request)
    {
        try {
            //获取IP 松耦合，不管返回值
            String ip = info.get("ip").toString();

            String frushFaceUrl = "" + "/fkbindface/FrushFaceRecord";

            Facedevice facedevice = faceDeviceServiceImpl.selectByIp(ip);
            if (facedevice != null) {
                String time = info.get("time").toString();
                Long ltime = Long.parseLong(time);
                Date d = new Date(ltime);
                time= DateUtil.dateToStringWithTime(d);
                //返回只有ID，在TDX设备中，ID和卡号一致。必须要有卡号，原因是卡号需要下发门禁
                String cardNo = info.get("personId").toString();
                FrushFaceRecord frushFaceRecord = new FrushFaceRecord(facedevice.getId(), facedevice.getInorout(), time, cardNo);
                String strJson = JSON.toJSONString(frushFaceRecord);
//                String respose = HTTP.post(frushFaceUrl, strJson);
//                logger.info(String.format("tdxcallback:ip:%s,return%s", ip, respose));
            }
        }catch (Exception e)
        {

            e.printStackTrace();
            logger.error(String.format("执行回调异常%s", e.getStackTrace()));
        }
        Map map = new HashMap();

        map.put("result",1);
        map.put("success",true);
        return map;
    }


    @ApiOperation(value = "用户注销", notes = "用户注销")
    @RequestMapping(value = "userfacecancel", method = RequestMethod.POST, produces = {"application/json"})
    public
    @ResponseBody
    ApiResult<String> userfacecancel(@RequestBody VisitorInfo visitorInfo,
                                     HttpServletRequest request) {
        ApiResult<String> result = new ApiResult<String>();
        List<Integer> failHQList = new ArrayList<Integer>();// 失败海清设备
        List<Integer> failHCList = new ArrayList<Integer>();// 失败的海康设备
        List<Integer> failTDXList = new ArrayList<Integer>();//失败的腾达迅设备
        List<Integer> failTDX8List = new ArrayList<Integer>();//失败的腾达迅设备
        try {
            String deviceIds = visitorInfo.getDeviceIds();
            if (StringUtils.isBlank(deviceIds)) {
                result.setCode(ApiResult.PARAM_ERROR);
                result.setMsg("设备id不能为空");
            } else {

                for (String deviceId : deviceIds.split(",")) {
                    if("null".equals(deviceId))
                    {
                        //有可能有垃圾数据
                        continue;
                    }
                    Integer devicdId_int =0;//
                    try {
                        devicdId_int = Integer.parseInt(deviceId);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                        result.getErrorResult(e);
                        continue;
                    }
                    Facedevice faceDevice = faceDeviceServiceImpl.selectByPrimaryKey(devicdId_int);
                    if(faceDevice == null)
                    {
                        continue;
                    }
                    switch (faceDevice.getModel()) {
                        case "TDX":
                        {
                            Map<String, String> tdxR =tdxFaceService.delCard(Integer.valueOf(deviceId), visitorInfo);
                            if (!tdxR.get("code").equals("1000")) {
                                failTDXList.add(devicdId_int);
                            }
                            break;
                        }
                        case "TDX8":
                        {
                            Map<String, String> tdxR =tdx8FaceService.delCard(Integer.valueOf(deviceId), visitorInfo);
                            if (!tdxR.get("code").equals("1000")) {
                                failTDX8List.add(devicdId_int);
                            }
                            break;
                        }
                        default:
                            break;
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.getErrorResult(e);
        }

        if (failHQList.size() > 0 || failHCList.size() > 0|| failTDXList.size()>0) {
            result.setCode(ApiResult.OPERATION_ERROR);
            result.setMsg("删除失败的设备 HQ：" + StringUtils.join(failHQList, ",") +
                    " HC设备有：" + StringUtils.join(failHCList, ",")+" TDX设备有："+StringUtils.join(failTDXList,",")+
                    " TDX8设备有："+StringUtils.join(failTDX8List,","));
        }

        return result;
    }


 

//    @ApiOperation(value = "获取设备信息", notes = "获取设备信息")
//    @RequestMapping(value = "getdevicesystem", method = RequestMethod.POST, produces = {"application/json"})
//    public
//    @ResponseBody
//    ApiResult getdevicesystem(@RequestBody Facedevice facedevice, HttpServletRequest request) {
//        ApiResult result = new ApiResult();
//
//        Map map = null;
//        try {
//            map = faceDeviceServiceImpl.GetSysParam(facedevice);
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error(String.format("执行获取设备信息接口异常%s", e.getStackTrace()));
//        }
//        if (map != null) {
//            result.setCode(Integer.parseInt(map.get("code").toString()));
//            result.setMsg(map.get("msg").toString());
//            result.setContent(map.get("content"));
//        } else {
//            result.setCode(9000);
//            result.setMsg("未知异常");
//        }
//        return result;
//    }




    /**
     * 开启设备验证监控
     *
     * @return
     */
    @ApiOperation(value = "开启设备验证监控", notes = "开启设备验证监控")
    @RequestMapping(value = "facedeviceverifytopic/{deviceId}", method = RequestMethod.GET, produces = {
            "application/json"})
    public
    @ResponseBody
    ApiResult<String> facedeviceverifytopic(@PathVariable Integer deviceId, HttpServletRequest request) {
        ApiResult result = new ApiResult();
        try {
            Facedevice facedevice = faceDeviceServiceImpl.selectByPrimaryKey(deviceId);
            if (facedevice != null) {
                if("TDX".equals(facedevice.getModel()))
                {
                    Map map = tdxFaceService.regisTopic(facedevice);
                    if (map != null && map.keySet().size() > 0) {
                        result.setCode(Integer.parseInt(map.get("code").toString()));
                        result.setMsg(map.get("msg").toString());
                    } else {
                        result.setCode(9000);
                        result.setMsg("未知异常");
                    }
                }
                else if("TDX8".equals(facedevice.getModel()))
                {
                    Map map = tdx8FaceService.regisTopic(facedevice);
                    if (map != null && map.keySet().size() > 0) {
                        result.setCode(Integer.parseInt(map.get("code").toString()));
                        result.setMsg(map.get("msg").toString());
                    } else {
                        result.setCode(9000);
                        result.setMsg("未知异常");
                    }
                }
            }
        } catch (Exception e) {
            result.getErrorResult(e);
            e.printStackTrace();
            logger.info("设备id:" + deviceId + " 开启监控失败", e);
        }
        return result;
    }


    /**
     * 取消设备验证订阅
     *
     * @return
     */
    @ApiOperation(value = "取消设备验证订阅", notes = "取消设备验证订阅")
    @RequestMapping(value = "facedeviceunsubscribetopic/{deviceId}", method = RequestMethod.GET, produces = {
            "application/json"})
    public
    @ResponseBody
    ApiResult<String> facedeviceunsubscribetopic(@PathVariable Integer deviceId, HttpServletRequest request) {
        ApiResult result = new ApiResult();
        try {
            Facedevice facedevice = faceDeviceServiceImpl.selectByPrimaryKey(deviceId);
            if (facedevice != null) {
                 if ("TDX".equals(facedevice.getModel()))
                {
                    Map map = tdxFaceService.deRegisTopic(facedevice);
                    if (map != null) {
                        result.setCode(Integer.parseInt(map.get("code").toString()));
                        result.setMsg(map.get("msg").toString());
                    } else {
                        result.setCode(9000);
                        result.setMsg("未知异常");
                    }
                }else if ("TDX8".equals(facedevice.getModel()))
                {
                    Map map = tdx8FaceService.deRegisTopic(facedevice);
                    if (map != null) {
                        result.setCode(Integer.parseInt(map.get("code").toString()));
                        result.setMsg(map.get("msg").toString());
                    } else {
                        result.setCode(9000);
                        result.setMsg("未知异常");
                    }
                }
            }
        } catch (Exception e) {
            result.getErrorResult(e);
            e.printStackTrace();
            logger.info("设备id:" + deviceId + " 开启监控失败", e);
        }
        return result;
    }

}
